package com.nanrui.mutualinductor;

import com.batman.baselibrary.base.BaseApplication;
import com.batman.baselibrary.data.result.AccountHelper;
import com.batman.baselibrary.delegate.ApplicationDelegate;
import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.network.http.HttpHandler;

import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyApplication extends ApplicationDelegate {


//    private RxBleClient rxBleClient;
//
//    /**
//     * In practice you will use some kind of dependency injection pattern.
//     */
//    public static RxBleClient getRxBleClient(Context context) {
//        MyApplication application = (MyApplication) context.getApplicationContext();
//        return application.rxBleClient;
//    }

    @Override
    public String getBaseUrl() {

//        return "http://47.111.156.249:8080/";
        return "https://zuul.njaiouwei.com/";
    }

    @Override
    public int getLevel() {
        return LEVEL_APP;
    }

    @Override
    public Class[] subDelegates() {
        return new Class[]{
                BaseApplication.class
        };
    }

    @Override
    public void onCreateDelegate() {

//        rxBleClient = RxBleClient.create(this);
//        RxBleClient.updateLogOptions(new LogOptions.Builder()
//                .setLogLevel(LogConstants.INFO)
//                .setMacAddressLogSetting(LogConstants.MAC_ADDRESS_FULL)
//                .setUuidsLogSetting(LogConstants.UUIDS_FULL)
//                .setShouldLogAttributeValues(true)
//                .build()
//        );

//        BleManager.getInstance().init(this);
//        RxJavaPlugins.setErrorHandler(throwable -> {
//            if (throwable instanceof UndeliverableException && throwable.getCause() instanceof BleException) {
//                Log.v("MyApplication", "Suppressed UndeliverableException: " + throwable.toString());
//                return; // ignore BleExceptions as they were surely delivered at least once
//            }
//            // add other custom handlers if needed
//            throw new RuntimeException("Unexpected Throwable in RxJavaPlugins error handler", throwable);
//        });

//        FlowManager.init(FlowConfig.builder(getApplicationContext())
//
//                .addDatabaseHolder(ExamComponentGeneratedDatabaseHolder.class)
//
//                .addDatabaseHolder(StudyComponentGeneratedDatabaseHolder.class)
//
//                .build());

        // 解决glide加载https证书问题
        try {
            Glide.get(this).getRegistry().replace(
                    GlideUrl.class, InputStream.class,
                    new OkHttpUrlLoader.Factory(getSSLOkHttpClient()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置https 访问的时候对所有证书都进行信任
     *
     * @throws Exception
     */
    private OkHttpClient getSSLOkHttpClient() throws Exception {
        final X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory, trustManager)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .build();
    }

    /**
     * 动态添加请求头
     */
    @Override
    protected HttpHandler getHttpHandler() {
        return new HttpHandler() {
            @Override
            public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
                return response;
            }

            @Override
            public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
                Request.Builder builder = request.newBuilder();

                builder.addHeader("token", AccountHelper.getToken());
                return builder.build();
            }
        };
    }
}
